package com.zzt.pagehelp.util

import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author: zeting
 * @date: 2022/10/26
 *
 */
class PageHelper<T>(
    val pageUi: PageUi<T>,
    val pager: Pager<T>,
) {
    init {

//        pageUi.refreshLayout.setOnRefreshListener { refreshLayout ->
//            pageUi.scope.launch {
//                val list = pager.refresh()
//                pageUi.adapter?.setList(list)
//                if (pager.pageState.noMore) {
//                    refreshLayout.finishRefreshWithNoMoreData()
//                } else {
//                    refreshLayout.finishRefresh()
//                }
//            }
//        }
//        pageUi.refreshLayout.setOnLoadMoreListener { refreshLayout ->
//            pageUi.scope.launch {
//                val list = pager.requestNext()
//                pageUi.adapter?.addData(list)
//                if (pager.pageState.noMore) {
//                    refreshLayout.finishLoadMoreWithNoMoreData()
//                } else {
//                    refreshLayout.finishLoadMore()
//                }
//            }
//        }

        pageUi.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageUi.scope.launch {
                    val list = pager.refresh()
                    pageUi.adapter?.setList(list)
                    if (pager.pageState.noMore) {
                        refreshLayout.finishRefreshWithNoMoreData()
                    } else {
                        refreshLayout.finishRefresh()
                    }
                }
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageUi.scope.launch {
                    val list = pager.requestNext()
                    pageUi.adapter?.addData(list)
                    if (pager.pageState.noMore) {
                        refreshLayout.finishLoadMoreWithNoMoreData()
                    } else {
                        refreshLayout.finishLoadMore()
                    }
                }
            }
        })

        pageUi.scope.launch {
            pager.pageState.noMoreFlow.collectLatest {
                pager.callNoMoreState(noMoreState = it)
            }
        }
    }

    /**
     * 代码控制刷新
     */
    fun refresh() {
        pageUi.refreshLayout.autoRefresh()
    }

    /**
     * 代码控制获取下一页
     */
    suspend fun requestNext() {
        pager.requestNext()
    }

    /**
     * 发送没有更多数据的状态
     *
     * 实验性api，不确定在实际使用中的逻辑效果是否能满足实际需求
     */
    @ExperimentalStdlibApi
    fun callNoMoreState(noMoreState: Boolean) {
        pager.callNoMoreState(noMoreState = noMoreState)
    }
}